import { Component, Prop, Vue, Emit, Watch } from 'vue-property-decorator'
import styles from './ApplyLicenseNumber.less'
import Upload from '@/components/Upload'
import ImagePreview from '@/components/ImagePreview'
import { ElForm } from 'element-ui/types/form'
import { IStatus, orgTypes, orgLicenseTypes } from '@/lib/sealFormat'

const fileTypes = ['image/jpeg', 'image/jpg', 'image/png']
const fileSizeLimit = 10
@Component({})
export default class ApplyInvoice extends Vue {
  @Prop({ default: false }) private visible!: boolean
  @Prop({ default: {} }) private defaultData!: any
  @Prop({ default: '' }) private currentOrganizeUUID!: string
  // @Prop({ default: {} }) private defaultData!: any;

  private imgVisible = false
  private uploadUrl: string = '/seal/rest/file/uploadPicMulti'
  private file: any = {
    status: 'init',
  }

  private applyLicenseNumberData: any = {
    organizeLicenseType: 2,
    licenseNumberSource: 2,
    licenseNumberFileKey: '',
    organizeLicenseNumber: '',
    organizeName: '',
  }

  private fileProgress(event: any, file: any, fileList: any[]) {
    this.file = Object.assign(
      {},
      {
        name: file.name,
        status: 'upload',
        size: file.size,
        precent: parseInt(file.percentage),
      }
    )
  }

  private uploadSuccess(response: any, file: any, fileList: any[]) {
    if (response.errCode === 0) {
      this.file = Object.assign(
        {},
        {
          name: file.name,
          status: 'done',
          size: file.size,
          url: URL.createObjectURL(file.raw),
        }
      )
      this.applyLicenseNumberData.licenseNumberFileKey = response.data.fileKey
    } else {
      this.file = {}
      this.applyLicenseNumberData.licenseNumberFileKey = ''
      this.$message.error(response.msg)
    }
  }

  private uploadError(err: any, file: any, fileList: any[]) {
    this.file = {}
    this.applyLicenseNumberData.licenseNumberFileKey = ''
    this.$message.error('文件上传失败')
  }

  private beforeUpload(file: any) {
    const isJPG =
      fileTypes.filter(
        (item: string) => item === (file.type || '').toLowerCase()
      ).length > 0
    const isLimit = file.size / 1024 / 1024 < fileSizeLimit
    if (!isJPG) {
      this.$message.error('格式须为 JPG/PNG/JPEG')

      return false
    }
    if (!isLimit) {
      this.$message.error(`申请表大小不能超过${fileSizeLimit}MB。`)

      return false
    }
    this.file = Object.assign(
      {},
      { name: file.name, status: 'upload', size: file.size, precent: 0 }
    )
  }

  private sealRules = {
    organizeLicenseNumber: [
      {
        required: true,
        message: '请输入证照号码',
        trigger: ['blur', 'change'],
      },
      { len: 18, message: '证照号码长度为18位', trigger: ['blur', 'change'] },
      {
        pattern: /^([0-9,A-Z,a-z]){18}$/,
        message: '证照号码格式不正确',
        trigger: 'blur',
      },
    ],
  }

  protected render(h: any) {
    return (
      <el-dialog
        class={styles.applyLicenseNumber}
        title="统一社会信用代码更新申请"
        custom-class="custom-dialog"
        visible={this.visible}
        close-on-click-modal={false}
        close-on-press-escape={false}
        width="442px"
        before-close={this.beforeClose}
      >
        <el-form
          ref="form"
          label-width="70px"
          {...{
            props: {
              model: this.applyLicenseNumberData,
              rules: this.sealRules,
            },
          }}
          hide-required-asterisk
        >
          <el-form-item label="机构名称">
            <el-input
              v-model={this.applyLicenseNumberData.organizeName}
              disabled
            />
          </el-form-item>

          <el-form-item label="机构类型">
            <el-select
              v-model={this.applyLicenseNumberData.organizeType}
              autocomplete="off"
              disabled
              placeholder=""
            >
              {orgTypes.map((orgType: IStatus, index: number) => (
                <el-option label={orgType.value} value={orgType.id} />
              ))}
            </el-select>
          </el-form-item>

          <el-form-item label="证照类型">
            <el-select
              v-model={this.applyLicenseNumberData.organizeLicenseType}
              disabled
            >
              {orgLicenseTypes.map((orgType: IStatus, index: number) => (
                <el-option label={orgType.value} value={orgType.id} />
              ))}
            </el-select>
          </el-form-item>

          <el-form-item label="证照号码" prop="organizeLicenseNumber">
            <el-input
              v-model={this.applyLicenseNumberData.organizeLicenseNumber}
              placeholder="请输入证照号码"
            />
          </el-form-item>

          <el-form-item
            label="上传社会信用代码证明材料"
            style="margin-top: 20px;"
          >
            <div class={styles.uploadContent}>
              <Upload
                file={this.file}
                progress={this.fileProgress}
                action={this.uploadUrl}
                success={this.uploadSuccess}
                error={this.uploadError}
                preview={this.preview}
                content="点击上传"
                beforeUpload={this.beforeUpload}
              />
              <div class={styles.tips}>
                上传须知: <br />
                1. 图片按照A4纸大小扫描，像素300dpi
                <br />
                2. 格式须为PNG/JPG/JPEG <br />
                3.
                为提高审核通过率请确保单位名称和统一社会信用代码清晰可见，且和申请表保持一致
              </div>
            </div>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button
            onClick={() => {
              this.beforeClose()
            }}
          >
            取 消
          </el-button>
          <el-button
            type="primary"
            onClick={() => {
              this.submit()
            }}
          >
            确 定
          </el-button>
        </span>
        <ImagePreview
          visible={this.imgVisible}
          title="证明材料预览"
          url={this.file.url}
          onVisibleChange={(val: boolean) => {
            this.imgVisible = val
          }}
        />
      </el-dialog>
    )
  }

  private submit() {
    ;(this.$refs.form as ElForm).validate((val: any) => {
      if (val) {
        if (!this.applyLicenseNumberData.licenseNumberFileKey) {
          this.$message.error('请上传社会信用代码证明材料')

          return
        }
        this.$emit('submit', this.applyLicenseNumberData)
        this.beforeClose()
      }
    })
  }

  private beforeClose() {
    this.$emit('visibleChange', false)
  }

  @Watch('visible')
  visibleHandler(val: boolean) {
    if (val) {
      this.applyLicenseNumberData.organizeLicenseType = 2
      this.applyLicenseNumberData.licenseNumberSource = 2
      if (this.currentOrganizeUUID !== this.defaultData.organizeUUID) {
        this.applyLicenseNumberData.licenseNumberFileKey = ''
        this.applyLicenseNumberData.organizeLicenseNumber = ''
        this.file = ''
        this.$nextTick(() => {
          ;(this.$refs.form as ElForm).clearValidate()
        })
      }
    }
  }

  @Emit('visibleChange')
  private visibleChange(val: boolean) {
    return val
  }

  private preview() {
    this.imgVisible = true
  }

  @Watch('defaultData.organizeType')
  organizeTypeHandler(val: number) {
    if (val) {
      this.applyLicenseNumberData.organizeType = val
    }
  }

  @Watch('defaultData.organizeName')
  organizeNameHandler(val: string) {
    if (val) {
      this.applyLicenseNumberData.organizeName = val
    }
  }
}
